package com.itcast.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.common.res.ResultCode;
import com.itcast.mapper.AddressMapper;
import com.itcast.pojo.Address;
import com.itcast.service.Addressservice;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.bind.ValidationException;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-06-19
 */
@Service("addressservice")
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements Addressservice {

    @Resource
    private AddressMapper mapper;

    @Override
    public int updateAddres(Map<String, String> map) throws ValidationException {
        Integer userId = Integer.valueOf(map.get("userId"));
        Address address=new Address();
        address.setUserId(userId);
        address.setAddresee(map.get("address"));
        address.setIsDefalut("1");

        Address addressInfo = mapper.selectOne(new QueryWrapper<Address>().eq("userId", userId).eq("isDefalut", "1"));
        int i;
        if (addressInfo!=null){
            address.setAid(addressInfo.getAid());
            address.setUpDates(new Date());
            i = mapper.updateById(address);
            if (i<1){
                throw new ValidationException(ResultCode.UPDATE_FAIL);
            }
        }else {
            address.setCreateDate(new Date());
            i = mapper.insert(address);
            if (i<1){
                throw new ValidationException(ResultCode.UPDATE_FAIL);
            }
        }


        return i;
    }

    @Override
    public Address getAddresByUserId(Integer userId) {
        Address address = mapper.selectOne(new QueryWrapper<Address>().eq("userId", userId).eq("isDefalut", "1"));
        return address;
    }
}
